import React, { useEffect, useState } from 'react';
import { Modal, Form, Input, Select, Upload, Image, message, DatePicker, Tabs, InputNumber, Switch } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { createActivity, updateActivity } from '@/services/contentManagementApi';
import { uploadImage } from '@/services/systemManagementApi';
import moment from 'moment';

const { RangePicker } = DatePicker;

interface ActivityFormProps {
  visible: boolean;
  mode: 'create' | 'edit';
  initialValues?: CONTENT.ActivityModel;
  onCancel: () => void;
  onSuccess: () => void;
}

const ActivityForm: React.FC<ActivityFormProps> = ({
  visible,
  mode,
  initialValues,
  onCancel,
  onSuccess,
}) => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [coverImageUrl, setCoverImageUrl] = useState<string>('');
  const [activeTab, setActiveTab] = useState('basic');

  useEffect(() => {
    if (visible) {
      if (mode === 'edit' && initialValues) {
        const formData = {
          ...initialValues,
          time_range: initialValues.start_time && initialValues.end_time 
            ? [moment(initialValues.start_time), moment(initialValues.end_time)]
            : undefined,
        };
        form.setFieldsValue(formData);
        setCoverImageUrl(initialValues.cover || '');
      } else {
        form.resetFields();
        setCoverImageUrl('');
      }
    }
  }, [visible, mode, initialValues, form]);

  // 处理表单提交
  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      setLoading(true);

      const submitData = {
        ...values,
        cover: coverImageUrl,
        start_time: values.time_range?.[0]?.format('YYYY-MM-DD HH:mm:ss'),
        end_time: values.time_range?.[1]?.format('YYYY-MM-DD HH:mm:ss'),
      };

      // 移除time_range字段
      delete submitData.time_range;

      if (mode === 'create') {
        await createActivity(submitData);
        message.success('活动创建成功');
      } else {
        await updateActivity(initialValues!.id, submitData);
        message.success('活动更新成功');
      }

      onSuccess();
    } catch (error) {
      message.error(mode === 'create' ? '活动创建失败' : '活动更新失败');
    } finally {
      setLoading(false);
    }
  };

  // 处理封面上传
  const handleCoverUpload = async (file: File) => {
    try {
      const response = await uploadImage(file);
      setCoverImageUrl(response.data.url);
      message.success('封面上传成功');
      return false;
    } catch (error) {
      message.error('封面上传失败');
      return false;
    }
  };

  const tabItems = [
    {
      key: 'basic',
      label: '基本信息',
      children: (
        <>
          <Form.Item
            name="title"
            label="活动标题"
            rules={[
              { required: true, message: '请输入活动标题' },
              { max: 100, message: '标题不能超过100个字符' },
            ]}
          >
            <Input placeholder="请输入活动标题" />
          </Form.Item>

          <Form.Item
            name="subtitle"
            label="副标题"
            rules={[{ max: 200, message: '副标题不能超过200个字符' }]}
          >
            <Input placeholder="请输入活动副标题" />
          </Form.Item>

          <Form.Item label="活动封面">
            <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
              {coverImageUrl && (
                <Image
                  src={coverImageUrl}
                  alt="活动封面"
                  width={120}
                  height={80}
                  style={{ objectFit: 'cover', borderRadius: 4 }}
                />
              )}
              <Upload
                showUploadList={false}
                beforeUpload={handleCoverUpload}
                accept="image/*"
              >
                <div style={{
                  width: 120,
                  height: 80,
                  border: '1px dashed #d9d9d9',
                  borderRadius: 4,
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  cursor: 'pointer',
                }}>
                  <div style={{ textAlign: 'center' }}>
                    <PlusOutlined />
                    <div style={{ marginTop: 8, fontSize: '12px' }}>上传封面</div>
                  </div>
                </div>
              </Upload>
            </div>
          </Form.Item>

          <Form.Item
            name="type"
            label="活动类型"
            rules={[{ required: true, message: '请选择活动类型' }]}
          >
            <Select placeholder="请选择活动类型">
              <Select.Option value="promotion">推广活动</Select.Option>
              <Select.Option value="competition">竞赛活动</Select.Option>
              <Select.Option value="festival">节日活动</Select.Option>
              <Select.Option value="learning">学习活动</Select.Option>
            </Select>
          </Form.Item>

          <Form.Item
            name="status"
            label="状态"
            rules={[{ required: true, message: '请选择状态' }]}
          >
            <Select placeholder="请选择状态">
              <Select.Option value="draft">草稿</Select.Option>
              <Select.Option value="published">进行中</Select.Option>
              <Select.Option value="ended">已结束</Select.Option>
              <Select.Option value="cancelled">已取消</Select.Option>
            </Select>
          </Form.Item>

          <Form.Item
            name="time_range"
            label="活动时间"
            rules={[{ required: true, message: '请选择活动时间' }]}
          >
            <RangePicker
              showTime
              format="YYYY-MM-DD HH:mm:ss"
              placeholder={['开始时间', '结束时间']}
              style={{ width: '100%' }}
            />
          </Form.Item>
        </>
      ),
    },
    {
      key: 'content',
      label: '内容描述',
      children: (
        <>
          <Form.Item
            name="description"
            label="活动简介"
            rules={[
              { required: true, message: '请输入活动简介' },
              { max: 500, message: '简介不能超过500个字符' },
            ]}
          >
            <Input.TextArea
              rows={4}
              placeholder="请输入活动简介"
              showCount
              maxLength={500}
            />
          </Form.Item>

          <Form.Item
            name="content"
            label="活动详情"
            rules={[{ required: true, message: '请输入活动详情' }]}
          >
            <Input.TextArea
              rows={8}
              placeholder="请输入活动详情"
            />
          </Form.Item>

          <Form.Item
            name="rules"
            label="活动规则"
          >
            <Input.TextArea
              rows={6}
              placeholder="请输入活动规则"
            />
          </Form.Item>

          <Form.Item
            name="rewards"
            label="奖励说明"
          >
            <Input.TextArea
              rows={4}
              placeholder="请输入奖励说明"
            />
          </Form.Item>
        </>
      ),
    },
    {
      key: 'settings',
      label: '活动设置',
      children: (
        <>
          <Form.Item
            name="max_participants"
            label="最大参与人数"
          >
            <InputNumber
              style={{ width: '100%' }}
              placeholder="请输入最大参与人数，0表示不限制"
              min={0}
            />
          </Form.Item>

          <Form.Item
            name="min_participants"
            label="最少参与人数"
          >
            <InputNumber
              style={{ width: '100%' }}
              placeholder="请输入最少参与人数"
              min={0}
            />
          </Form.Item>

          <Form.Item
            name="registration_fee"
            label="报名费用"
          >
            <InputNumber
              style={{ width: '100%' }}
              placeholder="请输入报名费用，0表示免费"
              min={0}
              precision={2}
              addonAfter="元"
            />
          </Form.Item>

          <Form.Item
            name="is_featured"
            label="是否推荐"
            valuePropName="checked"
          >
            <Switch />
          </Form.Item>

          <Form.Item
            name="allow_early_end"
            label="允许提前结束"
            valuePropName="checked"
          >
            <Switch />
          </Form.Item>

          <Form.Item
            name="auto_approve"
            label="自动审核"
            valuePropName="checked"
          >
            <Switch />
          </Form.Item>

          <Form.Item
            name="send_notifications"
            label="发送通知"
            valuePropName="checked"
          >
            <Switch />
          </Form.Item>

          <Form.Item
            name="tags"
            label="活动标签"
          >
            <Select
              mode="tags"
              placeholder="请输入活动标签"
              style={{ width: '100%' }}
            />
          </Form.Item>

          <Form.Item
            name="contact_info"
            label="联系方式"
          >
            <Input.TextArea
              rows={3}
              placeholder="请输入联系方式"
            />
          </Form.Item>

          <Form.Item
            name="external_url"
            label="外部链接"
            rules={[
              { type: 'url', message: '请输入有效的URL地址' },
            ]}
          >
            <Input placeholder="请输入外部链接" />
          </Form.Item>

          <Form.Item
            name="sort_order"
            label="排序"
          >
            <InputNumber
              style={{ width: '100%' }}
              placeholder="请输入排序值，数字越小越靠前"
              min={0}
            />
          </Form.Item>
        </>
      ),
    },
  ];

  return (
    <Modal
      title={mode === 'create' ? '新建活动' : '编辑活动'}
      open={visible}
      onCancel={onCancel}
      onOk={handleSubmit}
      confirmLoading={loading}
      width={800}
      destroyOnClose
    >
      <Form
        form={form}
        layout="vertical"
        initialValues={{
          type: 'learning',
          status: 'draft',
          registration_fee: 0,
          is_featured: false,
          allow_early_end: false,
          auto_approve: true,
          send_notifications: true,
          sort_order: 0,
        }}
      >
        <Tabs
          activeKey={activeTab}
          onChange={setActiveTab}
          items={tabItems}
        />
      </Form>
    </Modal>
  );
};

export default ActivityForm;
